package com.xxx.auth.service;

import com.xxx.auth.common.util.ApplicationGeneratorUtil;
import com.xxx.auth.common.util.DataUtil;
import com.xxx.auth.entity.Application;
import com.xxx.auth.entity.User;
import com.xxx.auth.repository.ApplicationRepository;
import com.xxx.auth.repository.PermissionRepository;
import com.xxx.auth.repository.UserRepository;
import com.xxx.auth.web.dto.ApplicationDTO;
import com.xxx.auth.web.vo.CreateApplicationForm;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@RequiredArgsConstructor
public class ApplicationService {

    private final ApplicationRepository applicationRepository;
    private final UserRepository userRepository;
    private final PermissionRepository permissionRepository;

    /**
     * 创建应用
     *
     * @param form 表单数据
     * @return 应用相关信息
     */
    public ApplicationDTO createApplication(CreateApplicationForm form) {
        Application application = new Application(form.getName(), form.getCreatorId());
        application.setDescription(form.getDescription() != null ? form.getDescription() : null);
        application.setAppSecret(ApplicationGeneratorUtil.generateAppSecret());
        application.getUserSet().add(DataUtil.getData(userRepository, form.getCreatorId(), User::getStatus));
        application.getPermissionSet().addAll(permissionRepository.findAll());

        applicationRepository.save(application);

        return new ApplicationDTO(application.getId(), application.getAppSecret());
    }

}
